<?php

namespace app\admin\controller\consult;

use app\admin\controller\Zlog;
use app\common\controller\Backend;
use app\common\logic\ChatManagerLogic;
use think\Db;
use think\Exception;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Reply extends Backend
{
    
    /**
     * Reply模型对象
     * @var \app\admin\model\consult\Reply
     */
    protected $model = null;
    protected $searchFields = 'reply.id,reply.name,o.name';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\consult\Reply;
        $this->view->assign("sexList", $this->model->getSexList());
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->assignconfig("org_cate_id", ORG_CATE_ID);
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where2 = $this->getSelfDataWhere('user.org_cate_id',true);
            $total = $this->model
                    ->with(['user','learncateteacher','consultroom'])
                ->join('edu_org_cate o','user.org_cate_id = o.id', 'left')
                ->where($where2)
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['user','learncateteacher','consultroom'])
                ->field('o.name as oname')
                ->join('edu_org_cate o','user.org_cate_id = o.id', 'left')
                ->where($where2)
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            foreach ($list as $key=>$row) {
                $row->sort = ($key+1+$offset);
                $row->has_teacher = ($row->teacher_id>0)?1:2;

            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row= $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                Db::startTrans();
                try{
                    $info = Db::name('consult_reply')->where('id', $ids)->field('*')->find();
                    if($info['teacher_id'] <= 0){
                        $this->error('请先设置老师！');
                    }
                    $params['process_time'] = time();
                    if($params['type'] == 1){
                        $room_mdl = new ChatManagerLogic();
                        $params['room_id'] = $room_mdl->create();
                        $room_mdl->open($params['room_id']);
                    }
                    $result = $row->save($params);
                    if ($result === false) {
                        $this->error($row->getError());
                    }
                    if($params['type'] == 1){
                        $sms['name'] = $info['name'];
                        $sms['tname'] = $info['teacher_name'];
                        $sms['time'] = date('Y-m-d H:i:s', $info['start_time']);
                        $alisms = new \addons\alisms\library\Alisms();
                        $config = config('config')['alisms'];
                        $res = $alisms->mobile($info['mobile'])
//                        ->template('SMS_175582712')
                            ->template($config['template']['notice2'])
                            ->sign($config['sign'])
                            ->param($sms)
                            ->send();
                        if ($res === false) {
                            Db::name('consult_reply')->where('id', $ids)->update(['type'=>0]);
                            $this->error('短信发送失败！');
                        }
                        $ip = request()->ip();
                        $sms = \app\common\model\Sms::create(['event' => 'reply', 'mobile' => $info['mobile'], 'content' => '亲爱的'.$sms['name'].'，您提交的咨询问题已经通过审核，安排老师'. $sms['tname'].'在'. $sms['time'].'跟您进行线上咨询，请准时跟老师在线沟通交流。', 'ip' => $ip, 'createtime' =>time()]);
                    }
                    Db::commit();
                }catch (Exception $e){
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error();
        }
        $this->view->assign("row", $row);
        $room = Db::name('consult_room')->where('id', $row->consult_room_id)->find();
        $this->view->assign("room", $room);
        return $this->view->fetch();
    }
    public function source(){
            $list = Db::name('consult_room')->field('name')->select();
            $json = json($list);
        return $json;
    }
    public function complete($ids = null)
    {
        $params = $this->request->post();
        if (isset($params['ids']) && !empty($params['ids'])) {
            $res = $this->model->where('id', 'in', $params['ids'])->update(['type'=>4]);
            if($res===false){
                $this->error($this->model->getError());
            }
            $this->success();
        }
        $this->error('编号错误！');
    }

    /*
     * 编辑家长学员
     * @param null $ids
     * @return string
     */
    public function chakan($ids = null)
    {
        $row= $this->model->get(['id' => $ids]);

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign("row", $row);
        $room = Db::name('consult_room')->where('id', $row->consult_room_id)->find();
        $this->view->assign("room", $room);
        return $this->view->fetch();
    }
    /**
     * 设置老师
     */
    public function teacher($ids = null)
    {
        $row= $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $total = Db::name('third')->where('id', $params['teacher_id'])->count();
                if($total <= 0){
                    $this->error('该用户id不存在！');
                }
                $result = $row->save($params);
                if ($result === false) {
                    $this->error($row->getError());
                }
                $this->success();
            }
            $this->error();
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 搜索下拉列表
     */
    public function searchlist()
    {
        $where2 = $this->getSelfDataWhere('org_cate_id');
        $list = Db::name('consult_room')->where($where2)->select();
        $searchlist = [];
        foreach ($list as $key => $value) {
            $searchlist[] = ['id' => $value['name'],'name' => $value['name']];
        }
        $data = ['searchlist' => $searchlist];
        $this->success('', null, $data);
    }
}
